//
//  DestinationViewController.m
//  RoadLine
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 RedFireNoodles. All rights reserved.
//

#import "DestinationViewController.h"
#import "TripListViewController.h"
#import "DestinationTblCell.h"
#import "PlaceModel.h"
#import "CityModel.h"
#import "ContryModel.h"
#import "AFHTTPRequestOperationManager.h"
#import "UIImageView+WebCache.h"
#import "DestDetailViewController.h"
#import "BaseTableView.h"
#import "PlaceDetailViewController.h"
#import "BaseView.h"
#import "MJRefresh.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface DestinationViewController ()

@property(nonatomic, retain)NSMutableArray *destArray;
// 该画面的字典(key－>section的title,value为section下的数组)
//@property(nonatomic, retain)NSMutableDictionary *destDic;
// 目的地画面的tableView
@property(nonatomic, retain)BaseTableView *destTblView;
// 菊花
@property(nonatomic, retain)UIActivityIndicatorView *activity;

@end

@implementation DestinationViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
//        self.destDic = [NSMutableDictionary dictionary];
        self.activity = [[UIActivityIndicatorView alloc] init];
        self.destArray = [NSMutableArray array];
    }
    return self;
}

- (void)parseData {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // 目的地tabBar的数据的接口
    NSString *strURL = @"http://api.breadtrip.com/destination/v3/";
    
    [manager GET:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.destArray removeAllObjects];
        NSArray *array = responseObject[@"elements"];
        for (NSDictionary *dic in array) {
            if ([dic[@"index"] integerValue] == 0) {
                NSMutableDictionary *destDic = [NSMutableDictionary dictionary];
                NSMutableArray *placeArray = [NSMutableArray array];
                for (NSDictionary *dicValue in dic[@"data"]) {
                    // 地点
                    PlaceModel *placeMdl = [[PlaceModel alloc] init];
                    [placeMdl setValuesForKeysWithDictionary:dicValue];
                    [placeArray addObject:placeMdl];
                    [placeMdl release];
                }
                [destDic setObject:placeArray forKey:dic[@"title"]];
                [self.destArray addObject:destDic];
            }
            else if ([dic[@"index"] integerValue] == 2) {
//                NSMutableArray *cityArray = [NSMutableArray array];
//                for (NSDictionary *dicValue in dic[@"data"]) {
//                    // 城市
//                    CityModel *cityMdl = [[CityModel alloc] init];
//                    [cityMdl setValuesForKeysWithDictionary:dicValue];
//                    [cityArray addObject:cityMdl];
//                    [cityMdl release];
//                }
//                [self.destDic setObject:cityArray forKey:dic[@"title"]];
            } else {
                NSMutableDictionary *destDic = [NSMutableDictionary dictionary];
                NSMutableArray *countryArray = [NSMutableArray array];
                for (NSDictionary *dicValue in dic[@"data"]) {
                    // 国家
                    ContryModel *countryMdl = [[ContryModel alloc] init];
                    [countryMdl setValuesForKeysWithDictionary:dicValue];
                    [countryArray addObject:countryMdl];
                    [countryMdl release];
                }
                [destDic setObject:countryArray forKey:dic[@"title"]];
                [self.destArray addObject:destDic];
            }
        }
        [self.activity stopAnimating];
        [self.destTblView reloadData];
        [self.destTblView.header endRefreshing];
//        UIButton *refreshBtn = (UIButton *)[self.destTblView viewWithTag:4040];
//        [refreshBtn removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.destTblView.header endRefreshing];
//        UIButton *refreshBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//        refreshBtn.frame = CGRectMake(0, 0, 140, 40);
//        refreshBtn.center = CGPointMake(WIDTH/ 2, HEIGHT / 2);
//        [refreshBtn setTitle:@"重新加载" forState:UIControlStateNormal];
//        [refreshBtn addTarget:self action:@selector(refreshBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//        refreshBtn.tag = 4040;
//        [self.destTblView addSubview:refreshBtn];
    }];
}

- (void)refreshBtnClick:(id)sender {
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    [self parseData];
    // 解析数据
    
    // 目的地TableView 铺满整个画面
    self.destTblView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) style:UITableViewStyleGrouped];
    self.destTblView.dataSource = self;
    self.destTblView.delegate = self;
    self.destTblView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.destTblView.alwaysBounceVertical = YES;
    [self.view addSubview:self.destTblView];
    [_destTblView release];
    
    [self.destTblView addLegendHeaderWithRefreshingBlock:^{
        [self parseData];
    }];
    
//    void (^refreshBtnClick)() = ^(){
//        [self parseData];
//    };
    
    //修改uinavigationBar的字体颜色为白色
    UILabel *titleLabelPrice = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleLabelPrice.font = [UIFont boldSystemFontOfSize:18];
    titleLabelPrice.textColor = [UIColor whiteColor];
    titleLabelPrice.backgroundColor = [UIColor clearColor];
    titleLabelPrice.text = @"     目的地";
    self.navigationItem.titleView = [titleLabelPrice autorelease];
    
    self.activity.frame = CGRectMake(0, 0, 240, 240);
    self.activity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [self.view addSubview:self.activity];
    [self.view bringSubviewToFront:self.activity];
    self.activity.center = CGPointMake(WIDTH / 2, HEIGHT / 2);
    [self.activity startAnimating];
    [_activity release];
    
    if ([Singleton shareSingleton].isNight) {
        [[Singleton shareSingleton] loadNightModeInfoFormDisk];
    }
}

// 目的地画面有多少个分类
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // 将目的地画面所有分类名全放到destKeyArray数组里
//    NSArray *destTypeArray = self.destDic.allKeys;
    // 有多少分组名就有多少分组
    return [self.destArray count];
}
// 每个分组下有多少个(国家,城市,景点)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // 将目的地画面所有分类名全放到destKeyArray数组里
    NSArray *destTypeArray = [self.destArray[section] allKeys];
    // 分组的Key
    NSString *sectionName = destTypeArray[0];
    // 通过分组的key找到对应内容的数组
    NSArray *array = [self.destArray[section] objectForKey:sectionName];
    // 返回数组长度
    return [array count];
}
// 目的地cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"destinationTblCell";
    DestinationTblCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[DestinationTblCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
    if ([Singleton shareSingleton].isNight) {
        [[Singleton shareSingleton] loadNightModeInfoFormDisk];
    }
    // 将目的地画面所有分类名全放到destKeyArray数组里
    NSArray *destTypeArray = [self.destArray[indexPath.section] allKeys];
    // 分组的Key
    NSString *sectionName = destTypeArray[0];
    // 通过分组的key找到对应内容的数组
    NSArray *array = [self.destArray[indexPath.section] objectForKey:sectionName];
    // 目的地名
    cell.nameLbl.text = [array[indexPath.row] name];
    // 有多少人喜欢
    cell.wish_to_goLbl.text = [NSString stringWithFormat:@"有多少人喜欢:%ld", [array[indexPath.row] wish_to_go_count]];
    // 有多少人去过
    cell.visited_countLbl.text = [NSString stringWithFormat:@"有多少人去过:%ld", [array[indexPath.row] visited_count]];
    // 图片占位图:
    [cell.destImgView sd_setImageWithURL:[NSURL URLWithString:[array[indexPath.row] cover_s]] placeholderImage:[UIImage imageNamed:@""]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

// cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = HEIGHT * 150 / 667;
    return height;
}
// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // 将目的地画面所有分类名全放到destKeyArray数组里
    NSArray *destTypeArray = [self.destArray[indexPath.section] allKeys];
    // 分组的Key
    NSString *sectionName = destTypeArray[0];
    // 通过分组的key找到对应内容的数组
    NSArray *array = [self.destArray[indexPath.section] objectForKey:sectionName];
    // 如果是国家
    if ([array[indexPath.row] isKindOfClass:[ContryModel class]]) {
        DestDetailViewController *destDetail = [[DestDetailViewController alloc] init];
        destDetail.hidesBottomBarWhenPushed = YES;
        ContryModel *country = array[indexPath.row];
        // 地点id
        destDetail.destId = [country countryId];
        // 地点类型
        destDetail.type = [NSString stringWithFormat:@"%ld", [country type]];
        [self.navigationController pushViewController:destDetail animated:YES];
        [destDetail release];
    // 如果是城市
    } else if ([array[indexPath.row] isKindOfClass:[CityModel class]]){
        DestDetailViewController *destDetail = [[DestDetailViewController alloc] init];
        destDetail.hidesBottomBarWhenPushed = YES;
        CityModel *city = array[indexPath.row];
        // 地点id
        destDetail.destId = [NSString stringWithFormat:@"%@", [city cityId]];
        // 地点类型
        destDetail.type = [NSString stringWithFormat:@"%ld", [city type]];
        [self.navigationController pushViewController:destDetail animated:YES];
        [destDetail release];
    } else {
        PlaceDetailViewController *placeDetailVC = [[PlaceDetailViewController alloc] init];
        PlaceModel *place = array[indexPath.row];
        placeDetailVC.hidesBottomBarWhenPushed = YES;
        // 类型
        placeDetailVC.type = [NSString stringWithFormat:@"%ld", place.type];
        // 地点id
        placeDetailVC.placeId = [NSString stringWithFormat:@"%@", place.placeId];
        [self.navigationController pushViewController:placeDetailVC animated:YES];
        [placeDetailVC release];
    }
    if ([Singleton shareSingleton].isNight) {
        [[Singleton shareSingleton] loadNightModeInfoFormDisk];
    }
}
// 返回的sectionView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    BaseView *sectionView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
//    sectionView.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:245/255.0 alpha:1];
    UILabel *sectionNamelbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, WIDTH - 20, 40)];
    sectionNamelbl.backgroundColor = [UIColor clearColor];
    // 将目的地画面所有分类名全放到destKeyArray数组里
    NSArray *destTypeArray = [self.destArray[section] allKeys];
    // 分组的Key
    NSString *sectionName = destTypeArray[0];
    // 返回名字
    sectionNamelbl.text = sectionName;
    sectionNamelbl.font = [UIFont systemFontOfSize:24];
    // 如果是3.5寸屏幕
    if (HEIGHT < 440) {
        sectionNamelbl.font = [UIFont systemFontOfSize:14];
    }
//    [sectionView addSubview:sectionNamelbl];
//    [sectionNamelbl release];
    return sectionNamelbl;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    CGFloat height = HEIGHT * 60 / 667;
    return height;
}

- (void)setLightDayModel {
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:246/255.0 green:85/255.0 blue:91/255.0 alpha:1];
}

- (void)setNightDayModel {
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:4/255.0 green:165/255.0 blue:171/255.0 alpha:1];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
//    [_destDic release];
    [_destArray release];
    [_destTblView release];
    [_activity release];
    [super dealloc];
}

@end
